package com.acmetelecom;

import org.joda.time.DateTime;

public class DurationCalculator {
	private static final int intersection1 = 7;
	private static final int intersection2 = 19;
	private int peakSeconds;
	private int offpeakSeconds;
	private DateTime start;
	private DateTime end;

	public DurationCalculator(DateTime start, DateTime end)
	{
		this.start = start;
		this.end = end;
		calculateDuration();
	}

	private void calculateDuration() {
		DateTime current = start;
    	DateTime next = getNextSwitchPointfor(current);
    	System.out.println(next.getMillis()+" "+current.getMillis());
    	while(true) {
			if(next.isAfter(end)) {
				if(offPeak(current))
					offpeakSeconds += Math.ceil((end.getMillis()-current.getMillis())/1000.0);
				else
					peakSeconds += Math.ceil((end.getMillis()-current.getMillis())/1000.0);
				break;
			}
			else {
				if(offPeak(current))
					offpeakSeconds += Math.ceil((next.getMillis()-current.getMillis())/1000.0);
				else
					peakSeconds += Math.ceil((next.getMillis()-current.getMillis())/1000.0);
				current = next;
				next = getNextSwitchPointfor(current);
			}
    	}
		System.out.println("peakSeconds:" + peakSeconds);
		System.out.println("offpeakSeconds:" + offpeakSeconds);		
	}

	private DateTime getNextSwitchPointfor(DateTime time) {
		int hour = time.getHourOfDay();
		DateTime t = time.withTimeAtStartOfDay();
		if(hour < intersection1)
			return t.withHourOfDay(intersection1);
		else if(hour >= intersection1 && hour < intersection2)
			return t.withHourOfDay(intersection2);
		return t.plusDays(1).withHourOfDay(intersection1);
	}
    
    private boolean offPeak(DateTime time) {
    	int hour = time.getHourOfDay();
        return hour < intersection1 || hour >= intersection2;
    }

	public int getPeakSeconds() {
		return this.peakSeconds;
	}

	public int getOffPeakSeconds() {
		return this.offpeakSeconds;
	}
}
